import { Card, Form, Input, Button, Checkbox } from 'antd'
import logo from '@/assets/logo.png'
import './index.scss'
import { useHistory } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { loginAction } from '@/store/actions/login.js'

function Login () {
  const history = useHistory()
  const dispatch = useDispatch()
  // 手机号校验规则
  const mobileRules = [
    { required: true, message: '手机号不能为空' },
    {
      pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
      message: '手机号格式不正确'
    }
  ]
  // 验证码校验规则
  const codeRules = [
    { required: true, message: '验证码不能为空' },
    { len: 6, message: '验证码长度为6位' }
  ]
  // 用户协议校验规则
  const agreeRules = [
    {
      validator: (_, value) =>
        value
          ? Promise.resolve()
          : Promise.reject(new Error('请阅读并同意用户协议'))
    }
  ]
  // 表单校验成功的回调
  const onFinish = async values => {
    const { mobile, code } = values
    await dispatch(loginAction(mobile, code))
    history.push('/')
  }

  return (
    <div className='login'>
      <Card className='login-container'>
        <img className='login-logo' src={logo} alt='' />
        {/* 表单 */}
        <Form
          initialValues={{ mobile: '13911111111', code: '246810', agree: true }}
          onFinish={onFinish}
          autoComplete='off'
          validateTrigger={['onChange', 'onBlur']}
        >
          <Form.Item name='mobile' rules={mobileRules}>
            <Input size='large' />
          </Form.Item>
          <Form.Item name='code' rules={codeRules}>
            <Input size='large' />
          </Form.Item>
          <Form.Item name='agree' valuePropName='checked' rules={agreeRules}>
            <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
          </Form.Item>
          <Form.Item>
            <Button type='primary' size='large' block htmlType='submit'>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
